﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectSubmitActivity : WebActivity
    {
        public static String Save(Array cells, ulong projectid, Uri url)
        {

            if (cells == null)
            {
                return "[]";
            }
            var webr = UMC.Web.WebResource.Instance();
            var domain = webr.WebDomain();// webr.Provider["domain"] ?? "localhost";//().TrimEnd('/');
            if (String.IsNullOrEmpty(domain))
            {
                return Data.JSON.Serialize(cells);
            }
            var list = new Dictionary<String, Uri>();

            var sp = UMC.Data.Utility.TimeSpan();

            foreach (var o in cells)
            {
                var pom = o as Hashtable;

                var Cname = pom["type"] as string ?? "";

                switch (Cname)
                {
                    case "CMSImage":
                        var value = pom["value"] as Hashtable;
                        if (value == null)
                        {
                            value = (pom["value"] as WebMeta).GetDictionary();
                        }

                        var src = new Uri(value["src"] as string);

                        if (domain.Contains(src.Host) == false)
                        {
                            if (src.Host.StartsWith("www.365lu.cn"))
                            {
                                value["src"] = $"{url.Scheme}://{domain}{src.PathAndQuery}";
                            }
                            else
                            {
                                var jpg = ".jpg";
                                var ex = src.AbsolutePath.LastIndexOf(".");
                                if (ex > -1)
                                {
                                    jpg = src.AbsolutePath.Substring(ex);
                                }
                                var gk = new Guid(UMC.Data.Utility.MD5(src.AbsoluteUri));
                                var srcKey = $"UserResources/{projectid}/{gk}{jpg}";
                                value["src"] = $"{url.Scheme}://{domain}/{srcKey}";
                                list[srcKey] = src;
                            }

                        }

                        break;
                }
            }

            try
            {
                var em = list.GetEnumerator();
                while (em.MoveNext())
                {
                    webr.Transfer(em.Current.Value, em.Current.Key);

                }
            }
            catch (Exception ex)
            {
                Utility.Error("Subject/image", ex.StackTrace);
            }

            return Data.JSON.Serialize(cells);
        }

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var subValue = request.SendValues;
            var user = this.Context.Token.Identity();

            var sub = new Subject();
            UMC.Data.Reflection.SetProperty(sub, subValue.GetDictionary());
            var content = new SubjectContent();

            sub.IsPicture = sub.IsPicture ?? false;

            var oldSub = DataFactory.Instance().Subject(sub.Id.Value);

            content.Id = sub.Id.Value;
            if (oldSub != null)
            {
                if (oldSub.project_id.HasValue)
                {
                    sub.project_id = oldSub.project_id;
                    var member = DataFactory.Instance().ProjectMember(oldSub.project_id.Value, user.Id.Value);
                    if (member != null)
                    {
                        switch (member.AuthType)
                        {
                            case WebAuthType.Admin:
                            case WebAuthType.User:
                                break;
                            default:
                                this.Prompt("您未有编辑此图文的权限");
                                break;
                        }

                    }
                    else
                    {
                        this.Prompt("您未有编辑此图文的权限");
                    }

                    sub.last_user_id = user.Id;

                    sub.LastDate = DateTime.Now;

                    if (oldSub.last_user_id != user.Id)
                    {
                        DataFactory.Instance().Put(new ProjectDynamic
                        {
                            Time = Utility.TimeSpan(sub.LastDate.Value),
                            user_id = user.Id,
                            Explain = "更新了文档",
                            Alias = user.Alias,
                            project_id = oldSub.project_id,
                            refer_id = oldSub.Id,
                            Title = oldSub.Title,
                            Type = DynamicType.Subject
                        });
                    }

                }
                DataFactory.Instance().Put(sub);

            }
            else
            {
                if (String.IsNullOrEmpty(sub.Title) == false)
                {
                    var celss = UMC.Data.JSON.Deserialize(content.DataJSON) as Array;
                    sub.Title = String.Format("{0:yyyy-MM-dd hh:mm}", DateTime.Now);
                    if (celss != null && celss.Length > 0)
                    {

                        var pom = celss.GetValue(0) as Hashtable;

                        var Cname = pom["type"] as string ?? "";
                        if (Cname == "CMSText")
                        {
                            var format = pom["format"] as Hashtable;
                            var value = pom["value"] as Hashtable;
                            if (value == null)
                            {
                                value = (pom["value"] as WebMeta).GetDictionary();
                            }

                            sub.Title = Utility.Format((format["text"] as string) ?? "{text}", value);
                        }

                    }
                }
                sub.Reply = 0;
                sub.Favs = 0;
                sub.Look = 0;
                sub.user_id = user.Id;
                sub.IsPicture = false;

                sub.Poster = user.Alias;
                sub.Code = Utility.Parse36Encode(Utility.IntParse(sub.Id.Value)[1]);
                sub.LastDate = DateTime.Now;
                sub.last_user_id = user.Id;

                SubjectSaveActivity.Dashboard(user, sub, this.Context.AppKey ?? Guid.Empty);
                DataFactory.Instance().Put(sub);


            }
            if (subValue.ContainsKey("Markdown"))
            {
                String Markdown = subValue["Markdown"];
                if (String.Equals(Markdown, "none") == false)
                {
                    content.ContentType = "markdown";
                    content.Content = Markdown;
                    var cells = Data.Markdown.Transform(Markdown);
                    var dlist = new ArrayList();
                    foreach (var d in cells)
                    {
                        dlist.Add(new WebMeta().Put("type", d.Type).Put("value", d.Data).Put("format", d.Formats).Put("style", d.Style).GetDictionary());

                    }

                    content.DataJSON = Save(dlist.ToArray(), sub.project_id ?? 0, request.Url);

                    DataFactory.Instance().Put(content);
                }


            }
            else if (subValue.ContainsKey("DataJSON"))
            {

                content.ContentType = "text/html";

                content.DataJSON = Save(Data.JSON.Deserialize(subValue["DataJSON"].Replace((char)160, ' ')) as Array, sub.project_id ?? 0, request.Url);

                DataFactory.Instance().Put(content);
            }

            this.Context.Send("Subject.Submit", new WebMeta().Put("time", DateTime.Now.ToShortTimeString()).Put("timespan", Utility.TimeSpan()).Put("id", content.Id), true);
        }



    }
}